<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>4-1 任务 网页涂鸦板</title>
</head>

<body>
    <div style="text-align: center;">
        <canvas id="cansElem">

        </canvas>
        <footer>by hjy 0424 <br>2023-11-13</footer>
    </div>
    <script>
        //获得画布对象，设置画布属性
        var canvas = document.getElementById('cansElem');
        canvas.width = 900;
        canvas.height = 600;
        canvas.style.border = '2px solid DarkTurquoise';
        //准备画笔，获取上下文
        var context = canvas.getContext('2d');
        context.lineWidth = '3';
        context.strokeStyle = 'pink';

        // 当鼠标按下触发onmousedown事件，驱动获取鼠标起始点坐标函数
        canvas.onmousedown = function(e) {
            console.log(canvas.getBoundingClientRect());
            console.log(e.clientX, e.clientY);

            var x = e.clientX - canvas.getBoundingClientRect().left;
            var y = e.clientY - canvas.getBoundingClientRect().top;
            context.beginPath(); //开始规划路径
            context.moveTo(x, y); //画笔起点位置

            // 当鼠标移动时触发onmousemove事件，驱动端点坐标的获取，进行绘制图像
            canvas.onmousemove = function(event) {
                console.log('绘图中...');


                var x = event.clientX - canvas.getBoundingClientRect().left;
                var y = event.clientY - canvas.getBoundingClientRect().top;
                context.lineTo(x, y);
                context.stroke(); //描边
            }

            // 当鼠标松开时触发onmouseup事件，onmousemove函数返回null，取消端点获取
            canvas.onmouseup = function() {
                console.log('取消绘制');
                canvas.onmousemove = null;
            }
        }
    </script>
</body>

</html>